<?php

namespace common\widgets\webuploader;

use yii\helpers\Html;
use yii\widgets\InputWidget;

class Webuploader extends InputWidget{
    //默认配置
    public $type;
    public $width = 0;
    public $height = 0;
    public $moreHiddenName = '';    //设置另外一个隐藏域的名称，供PHP后端程序灵活控制
    
    public function init()
    {
        parent::init();
        
        if($this->hasModel()){
            $attribute = $this->attribute;
            $this->value = $this->model->$attribute;
            $this->name = $this->attribute;
            $this->options['hiddenName'] = $this->model->formName().'['.$this->attribute.']';
        }else{
            
            //非activeForm方式的，也可以使用绑定模式，如name参数输入name='Designer[sex]'
            if (preg_match('/^[\s\S]+\[([\s\S]+)\]$/i', $this->name,$matches)) {    //如果是name='Designer[sex]'，则将hiddenName进行设置
                $this->options['hiddenName'] = $this->name;
                $this->name = $matches[1];
            }else{
                $this->options['hiddenName'] = '';
            }
            
        }
        
        WebuploaderAsset::register($this->view);
        
    }
    public function run()
    {   
        $directoryAsset = \Yii::$app->assetManager->getPublishedUrl('@common/widgets/webuploader/assets'); //获取Assets路径
        $value = $this->hasModel() ? Html::getAttributeValue($this->model, $this->attribute) : $this->value;
        
        return $this->render('main', [
            'type' => $this->type,
            'name' => $this->name,
            'hiddenName' => $this->options['hiddenName'],
            'value' => $this->value,
            'width' => $this->width,
            'height' => $this->height,
            'moreHiddenName' => $this->moreHiddenName,
            'directoryAsset' => $directoryAsset,
        ]);
    }


} 